# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

library(optparse)
library(ropls)
library(magrittr)
library(tidyverse)

option_list <- list(
  make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
  make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file")
)
opt <- parse_args(OptionParser(option_list = option_list))

data <- read.csv(opt$i, header = T, stringsAsFactors = F) %>%
  select(-c("HMDB", "KEGG", "Class")) %>%
  column_to_rownames("Metabolite")
data <- t(data) %>%
  as.data.frame()

print("=in=")
head(data)

sampleInfo <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
  select(c("SampleID", "ClassNote"))


df <- data %>%
  rownames_to_column("SampleID") %>%
  left_join(sampleInfo, by = c("SampleID")) %>%
  filter(ClassNote %in% sampleInfo$ClassNote) %>%
  column_to_rownames("SampleID")

x <- df %>%
  select(-c("ClassNote"))
crossValI <- min(nrow(x), 7)
pcaRs <- opls(x, plotL = F, crossvalI = crossValI)

modelDf <- pcaRs@modelDF %>%
  as_tibble()
if (nrow(modelDf) < 2) {
  pcaRs <- opls(x, plotL = F, crossvalI = crossValI, predI = 2)
}

parameterData <- pcaRs@modelDF %>%
  select(c(1:2)) %>%
  set_colnames(c("R2", "Cumulative R2")) %>%
  mutate(pcName = paste0("PC", 1:n())) %>%
  as_tibble() %>%
  column_to_rownames("pcName") %>%
  head(5) %>%
  t()
parameterData
write.csv(parameterData, paste0("PCA_with_All_Samples_R2.csv"), quote = FALSE)

pcData <- pcaRs@scoreMN %>%
  as.data.frame() %>%
  rownames_to_column("SampleID") %>%
  select("SampleID", num_range("p", 1:5)) %>%
  rename_at(vars(-c("SampleID")), function(x) {
    str_replace(x, "p", "PC")
  })

write.csv(pcData, paste0("PCA_with_All_Samples_Score.csv"), quote = FALSE, row.names = F)
